<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\Traits\EmailTrait;
use App\Http\Controllers\Api\Traits\SmsTrait;
use App\Models\Usages;
use Illuminate\Http\Request;
use App\Models\Corpcontact;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Mail;

class ContactController extends ApiController
{
    use SmsTrait,EmailTrait;

    private $expire_verifycode_time=2;//minute


    public function __construct(Request $request)
    {
        $this->middleware('throttle:10,1')->except(['storeCorpcontact','verificationCode','getVersionInfo','reportInfo']);
    }

    public function storeCorpcontact(Request $request,Corpcontact $corpcontact){
        $company = $request->post('compony', '');            //来自在线检测
        $p1 = $request->post('1', '');       //来自官网
        $p2 = $request->post('2', '');       //来自官网
        $p3 = $request->post('3', '');       //来自官网
        $p4 = $request->post('4', '');       //来自官网
        $p5 = $request->post('5', '');       //来自官网
        $products = (''==$p1)?'':'1:on;';
        $products .= (''==$p2)?'':'2:on;';
        $products .= (''==$p3)?'':'3:on;';
        $products .= (''==$p4)?'':'4:on;';
        $products .= (''==$p5)?'':'5:on;';
        $gtype = '';
        if (empty($company)) {
            $company = $request->post('componey', '');          //来自官网   
            $validcode = $request->post('validcode', '');       //来自官网

            if(empty($validcode)) {
                $job = $request->post('job', '');          //来自官网
                if(empty($job)) {
                    $gtype = 'wp';
                    $products = '5:on;';
                    $daywp = $request->post('0daywp', '');          //来自官网
                    if("1"==$daywp){
                        $gtype = '0dwp';
                        $products = '6:on;';
                    }elseif("3"==$daywp){
                        $gtype = 'pdwp';                      //产品白皮书
                        $products = '7:on;';
                    }else{
                        $mdps = $request->post('mdps-en', '');          //来自官网
                        if($mdps){
                            $gtype = 'mdps-en';                      //英文产品白皮书
                            $products = '8:on;';
                        }
                    }
                }else{
                    $gtype = 'mp';
                }
            }else{
                $manuals = $request->post('manuals', '');          //来自英文官网，申请手册
                $guidance = $request->post('guidance', '');          //来自英文官网，申请红蓝对抗指南
                if(!empty($manuals)){
                    $gtype = 'manuals';                      //英文产品手册
                    $products = '9:on;';
                }else if(!empty($guidance)){
                    $gtype = 'guidance';                      //英文红蓝对抗指南
                    $products = '10:on;';
                }
            }
        }
        if(empty($products)){
            $products = '3:on;';
        }
        $email = $request->post('email', '');
        $name = $request->post('name', '');
        $firstname = $request->post('first', '');
        $lastname = $request->post('last', '');        
        $phone = $request->post('phone', '');
        $country = $request->post('country', '');
        if(empty($name)){
            $name = $lastname.$firstname;
        }
        if(empty($phone)){
            $phone = $request->post('tphone', '');
        }
        $ip = $request->getClientIp();
        $sdata = [
            'company' => $company,
            'email' => $email,
            'name' => $name,
            'lastname' => $lastname,
            'phone' => $phone,
            'products' => $products,
            'country' => $country,	    
            'ip' => $ip
        ];
        $res = $corpcontact->updateOrCreate(['phone' => $phone],$sdata);
        $ref = $request->header('Referer');
        $sdata['ref'] = $ref;
        $sdata['gtype'] = $gtype;
        $this->sendSMTPMail($sdata);        
        return $this->success($res->id);
    }
    //通过短信或者邮箱发送验证码
    public function sendVerificationCode(Request $request)
    {
        $type = $request->get('type');
        $lan = $request->get('lang');

        $code = $this->generate_code();
        while (Cache::has($code)){
            Cache::forget($code);
            $code = $this->generate_code();
            sleep(1);
        }
        if(!Cache::has($code)){
            Cache::put($code,$request->getClientIp(),300);
        }
//        $verify_code = Redis::get();
        if($lan =='zh-CN'){
            $this->sendSmsSendHuaweiMes($type,[$code,$this->expire_verifycode_time]);
        }else{
            $this->sendEmailMsg($type,$code,$this->expire_verifycode_time);
        }
        return $this->success([
//            'code' => $code,
            'type' => $type
        ]);
    }
    //验证短信验证吗
    public function verificationCode(Request $request)
    {
        $code = $request->post('code');
        $lan  = $request->post('lang');
        if(Cache::has($code)){
            return $this->success('');
        }else{
            $msg = ($lan =='zh-CN')?'验证码无效':'Invalid Verification Code';
            return  $this->failed($msg);
        }
    }
    //生成指定长度的验证码
    protected function generate_code($length = 6) {
        return rand(pow(10,($length-1)), pow(10,$length)-1);
    }


    //pchunter 版本信息接口
    public function getVersionInfo()
    {
        $version = $this->getPchunterLatestVersion();
        $file_path = $version['file_path'];
        $file_path32 = $this->getPchunterLatestVersion("32")['file_path'];
        $keys = $version['keys'];
        $data = [
            "version" => "V".$keys,
            "system" => "Windows10_1909",
            "size" => count_file_size(filesize($file_path)+filesize($file_path32)),
            "date" => date("Y-m-d",filectime($file_path))
        ];
        return $this->success($data);
    }
    //获取pchunter 最新版本信息接口
    protected function getPchunterLatestVersion($dirctory="64")
    {
        $key_path = storage_path().DIRECTORY_SEPARATOR."pchunter_key".DIRECTORY_SEPARATOR."$dirctory".DIRECTORY_SEPARATOR;
        $file_array = scandir($key_path);
        unset($file_array[0],$file_array[1]);
        $latest_version = compare_file_array_version($file_array);
        $keys = array_keys($latest_version)[0];
        $value = $latest_version[$keys];
        $file_path = $key_path.$value;
        return [
            'keys' => $keys,
            'value' => $value,
            'file_path' => $file_path,
        ];
    }

    //上报信息接口
    public function reportInfo(Request $request)
    {
        $param = $request->get('param');
        $decode_string = base64_decode($param);
        $decode_array = explode('#*',$decode_string);

        $ip = $request->getClientIp();
        $machineid = $decode_array[0];
        $liscense = $decode_array[1];
        $osver = $decode_array[2];
        $version = $decode_array[3];
        $is_professional = $decode_array[4];

        $res = Usages::updateOrCreate([
            'machineid' => $machineid,
            'liscense' => $liscense
        ],[
            'ip'=> $ip,
            'machineid' => $machineid,
            'liscense' => $liscense,
            'osver' => $osver,
            'version' => $version,
            'is_professional' => $is_professional,
            'updated_at' => date('Y-m-d H:i:s')
        ]);
        $upgrade_file = storage_path().DIRECTORY_SEPARATOR."pchunter_key".DIRECTORY_SEPARATOR."pchunter_free";
        return response()->download($upgrade_file, 'pchunter_free', ['Content-Type' => 'application/download']);
    }
    protected function sendSMTPMail($sdata = [], $subject = '新来一条试用申请：', $from = 'zentao@anxinsec.com', $to = 'datamar@anxinsec.com')
    {
        //$to = '2298544907@qq.com';//收件方 ['a@qq.com','b@qq.com','c@qq.com'] 群发如此格式
        $products = $sdata['products'];
        $products = str_replace("1:on","安芯神甲智能内存保护系统",$products);
        $products = str_replace("2:on","系统信息检测工具",$products);        
        $products = str_replace("3:on","未知威胁文件检测系统",$products);
        if(empty($sdata['country'])){
            $products = str_replace("4:on","安芯神鉴终端保护系统",$products);
            $products = str_replace("5:on","应用安全防护系统RASP",$products);
        }else{
            $products = str_replace("4:on","Mobile Device Management",$products);
            $products = str_replace("5:on","Managed Security Service",$products);
        }

        if("mp"===$sdata["gtype"]){
            $products = "内存保护系统";
            $sdata["ref"] = "https://www.anxinsec.com/view/download/";
        }elseif("wp"===$sdata["gtype"]){
            $products = "白皮书下载";
            $sdata["ref"] = "https://www.anxinsec.com/view/download/";
        }elseif("0dwp"===$sdata["gtype"]){
            $products = "0day白皮书下载";
            $sdata["ref"] = "https://www.anxinsec.com/view/download/0day/";
        }elseif("pdwp"===$sdata["gtype"]){
            $products = "产品白皮书";
            $sdata["ref"] = "https://www.anxinsec.com/view/download/product/";
        }elseif("mdps-en"===$sdata["gtype"]){
            $products = "英文白皮书";
            $sdata["ref"] = "https://www.anxinsec.com/en/brochure-download/";
        }elseif("manuals"===$sdata["gtype"]){
            $products = "Company Product Manuals";
            $sdata["ref"] = "https://www.anxinsec.com/en/";
        }elseif("guidance"===$sdata["gtype"]){
            $products = "A Guidance for Defense Team";
            $sdata["ref"] = "https://www.anxinsec.com/en/";
        }
        $msg =
            "新来一条试用申请：".
        "\n邮箱：".$sdata['email'].
        "\n姓名：".$sdata['name'].
        "\n电话：".$sdata['phone'].
        "\n公司：".$sdata['company'].        
        "\n申请模块：".$products.
        "\n申请时间：".date('Y-m-d H:i:s').
        "\n客户端IP：".get_client_ip().
        "\n客户端URL：".$sdata["ref"].'';
        if (!empty($sdata)) {
            Mail::raw($msg, function ($message) use ($subject, $msg, $from, $to) {
                // 发件人（你自己的邮箱和名称）
                $message->from($from, 'anxin@email.com');
                // 收件人的邮箱地址
                $message->to($to);
                // 邮件主题
                $message->subject($subject);
            });
        }
    }    
}
